/*
App: MooVote
Author: Brendan Morante
Updated: 10/16/06
*/
 var MooVote = new Class({
     initialize: function(container, itemID, options) {
	 	
		this.options = Object.extend({
		  ratingStart: 0,
		  starClass: 'star',
		  messageBox: 'message',
		  busyMsg:'Sending your vote...',
		  votePath: 'vote.php',
		  overImg: '',
		  blankImg: '',
		  votedImg: ''
		}, options || {});
        this.container = $(container);
		this.itemID = itemID;
		this.current_rating = this.options.ratingStart;
		this.stars = $ES(".banana",this.container);
		this.enableStars();
		this.updateStars();
     },
	 
	 enableStars: function() {
	 	this.stars.each(function(star){
			star.onmouseover = function() { this.hover(star); }.bind(this);
			star.onmouseout = function() { this.unhover(); }.bind(this);
			star.onclick = function() { this.vote(star); }.bind(this);
		}, this);
	 },
	 
	 disableStars: function() {
		this.stars.each(function(star){
				star.onmouseover = Class.empty;
				star.onmouseout = Class.empty;
				star.onclick = Class.empty;
			});
	},
	 
	 findStarInArray:function(star) {
	 	var result;
		var i = 0;
		this.stars.each(function(el){
			if(el == star) {
				result = {index:i, star:el}; }
			i++;
	 	});
		return result;
	 },
     
	 hover: function(star, bSetRate) {
		try {
			var index = this.findStarInArray(star).index;
		} catch(err) { 
			var index = this.current_rating-1;
		}
		var z = 0;
		this.stars.each(function(star){
			if (z <= index && !bSetRate) {
				usestar = this.options.overImg; }
			else if(z <= index && bSetRate) {
				usestar = this.options.votedImg; }
			else {
				usestar = this.options.blankImg; }
			star.setAttribute("src", usestar);
			z++;
		}, this);
	},
	
	unhover: function() {
		this.updateStars();
	},
	
	updateStars: function() {
		this.hover(this.current_rating,true);
	},
	
	vote: function(star) {
		this.current_rating = this.findStarInArray(star).index+1;
		this.disableStars();
		this.unhover();
		this.sendRating();
	},
	
	sendRating: function() {
		var voteReq = new ajax(this.options.votePath, 
			{method:'post', postBody: 'op=vote&rating='+this.current_rating + "&item="+this.itemID, onComplete: this.onVoteComplete.bind(this)});
		this.setMessage(this.options.busyMsg);
		voteReq.request();
	},
	
	getRating: function() {
		var ratingReq = new ajax(this.options.votePath, 
			{method:'post', postBody: "op=getrating&item="+this.itemID, onComplete: this.ratingResponse.bind(this)});
		ratingReq.request();
	},
	
	ratingResponse: function(responseText) {
		var result = Json.evaluate(responseText);
		this.current_rating = result['voteTotal'];
		if(result['message']) {
			this.setMessage(result['message']); }
		this.unhover();
	},
	
	onVoteComplete: function(responseText) {
		this.ratingResponse(responseText);
		//this.setMessage("Thanks for voting!");
	},
	
	setMessage: function(msg) {
		var mb = $(this.options.messageBox);
		if(mb) {
			mb.innerHTML = msg; }
	}
	
  });